#include "syspara.h"

static SYSP_ST *pSysPara=NULL;

SYSP_ST *sys_para_get(void)
{
	return pSysPara;
}

u8 sys_para_set(SYSP_ST para)
{
	SYSP_ST sysp;	
	
	memset(&sysp,  0, sizeof(SYSP_ST));
	memcpy(&sysp, &para, sizeof(SYSP_ST));

	sysp.chksum = 0;
	sysp.chksum = chksum_xor8((u8 *)&sysp, sizeof(SYSP_ST));
	
	sys_debug("[SYS]%s, %d:::  chksum=%x\n", __func__, __LINE__, sysp.chksum);
	sys_debug("[SYS]%s, %d:::  refresh=%x\n", __func__, __LINE__, sysp.refresh);
	sys_debug("[SYS]%s, %d:::  ver=%s\n", __func__, __LINE__, sysp.ver);
	sys_debug("[SYS]%s, %d:::  test_val=%x\n", __func__, __LINE__, sysp.test_val);

	mml_sflc_erase(PARA_ADDR, PARA_OFT);
	iap_write_flash(PARA_ADDR, (u8 *)&sysp, sizeof(SYSP_ST));

	memset(pSysPara, 0, sizeof(SYSP_ST));
	memcpy(pSysPara, &sysp, sizeof(SYSP_ST));
	
	return 0;
}

u8 sys_default_set(void)
{
	SYSP_ST sysp;	

	memset(&sysp,  0, sizeof(SYSP_ST));

	sysp.refresh = SYS_REFrESH;
	sysp.upgrade = FALSE;
	memcpy(sysp.ver, SOFT_VER, strlen(SOFT_VER));
	sysp.ext_conf = 0x0f;
	sysp.int_conf = 0x07;
	
	// for test
	sysp.test_val = 0x123c;

	sysp.chksum = chksum_xor8((u8 *)&sysp, sizeof(SYSP_ST));
	
	sys_debug("[SYS] %s, %d::: chksum = %x\n", __func__, __LINE__, sysp.chksum);

	mml_sflc_erase(PARA_ADDR, PARA_OFT);
	iap_write_flash(PARA_ADDR, (u8 *)&sysp, sizeof(SYSP_ST));

	memset(pSysPara, 0, sizeof(SYSP_ST));
	memcpy(pSysPara, &sysp, sizeof(SYSP_ST));
	
	return 0;
}

u8 sys_para_init(void)
{
	SYSP_ST sysp;
	u8 chksum, bchksum;
	
	if(sizeof(SYSP_ST)>PARA_OFT){
		sys_debug("[SYS] syspara size more than %d !!!\n", PARA_OFT);
		while(1){}
	}

	pSysPara = (SYSP_ST *)pvPortMalloc( sizeof(SYSP_ST));
	if(!pSysPara){
		sys_debug("[SYS] malloc fail...\n");
		return 1;	
	}
	
	memset(&sysp, 0, sizeof(SYSP_ST));
	
	if(!mml_sflc_read(PARA_ADDR, (u8 *)&sysp, sizeof(SYSP_ST))){
		sys_debug("[SYS] get all sys para ok...\n");
	}else{
		sys_debug("[SYS] get all sys para fail...\n");
		return 2;
	}

	bchksum = sysp.chksum;
	sysp.chksum = 0;
	chksum = chksum_xor8((u8 *)&sysp, sizeof(SYSP_ST));
	sysp.chksum = bchksum;
	
	if((sysp.refresh != 0xa7b6) || (bchksum != chksum)){
		sys_default_set();
		sys_debug("[SYS] get all sys para fail, reset para...\n");
		return 2;
	}else{
		sys_debug("[SYS] get all sys para ok...\n");
	}

	memset(pSysPara, 0, sizeof(SYSP_ST));
	memcpy(pSysPara, &sysp, sizeof(SYSP_ST));
	sys_debug("[SYS] cmp:bchksum=%x,  pSysPara->chksum = %x, chksum=%x\n", bchksum, pSysPara->chksum, chksum);

	bchksum = 0x00;

	return 0;
}




